#include "head.h"

void userLogin(int net_fd, user_info *info, MYSQL *conn, pool_t *pool) {
    //recvInfoStruct(net_fd, info);
    printf("username:%s\npassword:%s\n",info->username, info->password);
    
    //char *sql_str;
    //sql_str = (char *)calloc(0, 1024);
    //sql_str = "select user_salt from user where user_id = ";
    char sql_str[4096];
    memset(sql_str, 0, sizeof(sql_str));
    sprintf(sql_str, "%s%s", "select * from user where user_id = ", info->username);
    printf("sql_str = %s\n", sql_str);

    pthread_mutex_lock(&pool->sql_lock);
    int ret_mysql_query = mysql_query(conn, sql_str);
    printf("mysql_query return%d\n", ret_mysql_query);
    MYSQL_ERROR_CHECK(conn, ret_mysql_query, 1);

    MYSQL_RES *result;
    result = mysql_store_result(conn);

    MYSQL_ROW row;
    row = mysql_fetch_row(result);
    if(row == NULL) {
        //没查到用户
        info->flag = 0;
        mysql_free_result(result);
        pthread_mutex_unlock(&pool->sql_lock);
        sendInfoStruct(net_fd, info);
    }
    else {
        info->flag = 1;
        sprintf(info->command_str_return, "%s", row[3]);
        mysql_free_result(result);
        pthread_mutex_unlock(&pool->sql_lock);
        
        //发送盐值让客户端拼密码后传回哈希
        sendInfoStruct(net_fd, info);

        //接收密码哈希
        recvInfoStruct(net_fd, info);
        printf("%s\n", info->password);
        
        pthread_mutex_lock(&pool->sql_lock);
        int ret_mysql_query = mysql_query(conn, sql_str);
        MYSQL_ERROR_CHECK(conn, ret_mysql_query, 1);
        
        result = mysql_store_result(conn);

        row = mysql_fetch_row(result);
        printf("hash=%s\n", row[2]);

        pthread_mutex_unlock(&pool->sql_lock);

        if(!strcmp(row[2], info->password)) {
            info->flag = 111;
        }
        else {
            //密码错误
            info->flag = 222;
        }
        sendInfoStruct(net_fd, info);

    }
    //printf("salt=%s\n", row[3]);


    //free(sql_str);
    
    return;
}
